import {Modal, View, Button, Toast} from '@ant-design/react-native';
import ItemList from '../../component/ItemList';
import UnitText from '../../component/UnitText';
import {
  launchImageLibrary,
  launchCamera,
  ImagePickerResponse,
} from 'react-native-image-picker';
import axios from '../../http/http';
import useStorage from '../../hooks/storage';
import {TUserInfo} from '../../type/TUser';

type TAvatar = {
  visible: boolean;
  close: (value: boolean) => void;
};
const Avatar: React.FC<TAvatar> = ({visible, close}) => {
  const userStorage = useStorage<TUserInfo>('userInfo');
  const avatarConf = [
    {title: '相册', id: 0},
    {title: '拍照', id: 1},
  ];
  const changeAvatar = (item: any) => {
    Toast.loading({
      content: '头像上传中',
      mask: false,
    });
    // const options = {
    //   title: '请选择',
    //   cancelButtonTitle: '取消',
    //   takePhotoButtonTitle: '拍照',
    //   chooseFromLibraryButtonTitle: '从相册选择',
    //   storageOptions: {
    //     skipBackup: true,
    //     path: 'images',
    //   },
    // };
    switch (item.title) {
      case '相册':
        ImageLibrary();
        break;
      case '拍照':
        camera();
        break;
      default:
        ImageLibrary();
    }
  };
  const camera = () => {
    launchCamera({mediaType: 'photo', saveToPhotos: true}, Response => {
      imageChoose(Response);
    });
  };
  const ImageLibrary = () => {
    launchImageLibrary({mediaType: 'photo'}, response => {
      imageChoose(response);
    });
  };
  const imageChoose = async (response: ImagePickerResponse) => {
    console.log('Response = ', response);
    if (response.didCancel) {
      return;
    }
    if (response.errorMessage) {
      Toast.info(response.errorMessage);
    }
    if (response.assets && response.assets[0]) {
      const userInfo = await userStorage.getItem();
      if (!userInfo) {
        Toast.removeAll();
        Toast.info({
          content: '请登录',
          mask: false,
        });
        return;
      }
      const {realname, id} = userInfo;
      const {uri, type, fileName} = response.assets![0];
      const formData = new FormData();
      formData.append('file', {
        uri,
        type,
        name: fileName,
      });
      formData.append('id', id);
      formData.append('realname', realname);
      axios
        .post('/user/update', formData, {
          'Content-Type': 'multipart/form-data',
        })
        .then(res => {
          if (res.error === -1) {
            Toast.removeAll();
            userStorage.setItem({...userInfo, avatar: res.data});
            close(false);
            Toast.info({
              content: '头像上传成功',
              mask: false,
            });
          }
        });
    }
  };
  return (
    <View>
      <Modal
        popup
        visible={visible}
        animationType="slide-up"
        maskClosable={true}
        onClose={() => close(false)}>
        <View>
          {avatarConf.map(item => (
            <ItemList key={item.id} onPress={() => changeAvatar(item)}>
              <View
                style={{
                  display: 'flex',
                  flexDirection: 'row',
                  height: 40,
                  width: '100%',
                  alignItems: 'center',
                  justifyContent: 'center',
                }}>
                <UnitText TStyle={{color: '#51a5f2', fontSize: 17}}>
                  {item?.title}
                </UnitText>
                {/* <Icon
                  name="arrow-right"
                  size="md"
                  color="#aaa"
                  style={{marginLeft: 16}}
                /> */}
              </View>
            </ItemList>
          ))}
        </View>
        <View
          style={{
            display: 'flex',
            alignItems: 'center',
            marginBottom: 20,
            height: 70,
            justifyContent: 'center',
          }}>
          <Button
            type="warning"
            style={{width: 150, height: 40}}
            onPress={() => close(false)}>
            取消
          </Button>
        </View>
      </Modal>
    </View>
  );
};
export default Avatar;
